import type { RouteRecordRaw } from 'vue-router'
import { defineStore } from 'pinia'
import { cloneDeep } from 'lodash-es'
import { constantRoutes } from '@/routes/routes'
import { getMenu } from '@/api/system'
import { arrayToTree } from '@/utils'
import { routeMapComponent } from '@/routes/routeMapComponent'

function hasPermission(roles: string[], route: RouteRecordRaw) {
  if (route.meta?.roles?.length)
    return roles.some(item => route.meta?.roles.includes(item))

  return true
}

function filterAsyncRouter(routerMap: any[], roles: string[]) {
  // 避免影响原始数据
  const cloneRouterMap = cloneDeep(routerMap)
  const accessedRouters = cloneRouterMap.filter((route: RouteRecordRaw) => {
    if (hasPermission(roles, route)) {
      if (route.children?.length)
        route.children = filterAsyncRouter(route.children, roles)

      return true
    }
    return false
  })
  return accessedRouters
}

const useRoutesStore = defineStore('routes', {
  state: () => ({
    permissionRoutes: constantRoutes,
    addRoutes: [] as any[],
  }),
  actions: {
    // 前端控制菜单
    async generateRoutes(roles: string[]) {
      const menuList = await getMenu()
      const list = menuList.data.map((menu: any) => {
        return {
          id: menu.id,
          pid: menu.pid,
          name: menu.name,
          path: menu.path,
          redirect: menu.redirect,
          active: menu.active,
          meta: { title: menu.metaTitle, icon: routeMapComponent[menu.path]?.icon, activeMenu: menu.metaActiveMenu, roles: menu.roles },
          component: routeMapComponent[menu.path]?.component,
        }
      })
      const asyncMenuList = arrayToTree(list, 0)

      return new Promise((resolve) => {
        let accessedRoutes = filterAsyncRouter(asyncMenuList, roles)
        // 父菜单没有子菜单时进行隐藏
        accessedRoutes = accessedRoutes.map((item: any) => {
          return {
            ...item,
            hideInMenu: item.pid === 0 && item.children.length === 0,
          }
        })
        this.addRoutes = accessedRoutes
        this.permissionRoutes = constantRoutes.concat(accessedRoutes)
        resolve(accessedRoutes)
      })
    },
    // 前端控制菜单
    // async generateRoutes(roles: string[]) {
    //   return new Promise((resolve) => {
    //     const accessedRoutes = filterAsyncRouter(asyncRoutes, roles)
    //     this.addRoutes = accessedRoutes
    //     this.permissionRoutes = constantRoutes.concat(accessedRoutes)
    //     resolve(accessedRoutes)
    //   })
    // },
  },
})

export default useRoutesStore
